<template>
	<el-dialog v-model="visible" title="地址信息" :close-on-click-modal="false">
		<el-form ref="dataFormRef" label-width="220" label-position="top" :rules="dataRules" :model="dataForm">
			<el-form-item label="地址类型" prop="addrTpCd">
				<fast-select
					:disabled="dataForm.id ? true : false"
					v-model="dataForm.addrTpCd"
					style="width: 100%"
					dict-type="mpi_addr_tp_cd"
					placeholder="请选择地址类型"
					clearable
					filterable
				></fast-select>
			</el-form-item>
			<el-form-item label="所在省市区" prop="addCodes">
				<el-cascader style="width: 100%" v-model="dataForm.addCodes" :options="options" clearable :props="addressData" @change="adcdChange" />
			</el-form-item>
			<!-- <el-form-item label="所在省份（自治区、直辖市）" prop="addrPrvCd">
				<el-select filterable v-model="dataForm.addrPrvCd" style="width: 100%" @change="provinceChange">
					<el-option v-for="(item, index) in provinceList" :key="index" :label="item.name" :value="item.code">{{
						item.name }}</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="所在市（地区、州）" prop="addrCtyCd">
				<el-select filterable v-model="dataForm.addrCtyCd" style="width: 100%" @change="cityChange">
					<el-option v-for="(item, index) in cityList" :key="index" :label="item.name" :value="item.code">{{
						item.name }}</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="所在县（区）" prop="addrCntyCd">
				<el-select filterable v-model="dataForm.addrCntyCd" style="width: 100%" @change="areaChange">
					<el-option v-for="(item, index) in areaList" :key="index" :label="item.name" :value="item.code">{{
						item.name }}</el-option>
				</el-select>
			</el-form-item> -->
			<el-form-item label="所在街道/镇" prop="addrTwnCd">
				<el-select v-model="dataForm.addrTwnCd" filterable style="width: 100%" @change="streeChange">
					<el-option v-for="(item, index) in streetList" :key="index" :label="item.name" :value="item.code">{{ item.name }}</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="所在村（街、路、弄等）" prop="addrVlgCd">
				<el-select v-model="dataForm.addrVlgCd" filterable style="width: 100%">
					<el-option v-for="(item, index) in villageList" :key="index" :label="item.name" :value="item.code">{{ item.name }}</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="门牌号" prop="addrHusNo">
				<el-input v-model="dataForm.addrHusNo" maxlength="50" placeholder="请输入门牌号"></el-input>
			</el-form-item>
			<el-form-item label="邮编" prop="postCd">
				<el-input v-model="dataForm.postCd" placeholder="请输入邮编"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" :loading="btnLoading" @click="subFormHandle">确定</el-button>
		</template>
	</el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useDictProviceDetailApi } from '@/api/patient-primary/index'
import { savePatientAddress } from '@/api/patient-primary/patient-mana'
import { ElMessage } from 'element-plus'
import { number } from 'echarts'
const visible = ref(false)
const btnLoading = ref(false)

const emit = defineEmits(['close'])

const dataForm = reactive({
	addrTpCd: '',
	addCodes: [],
	addrPrvCd: '',
	addrCtyCd: '',
	addrCntyCd: '',
	addrTwnCd: '',
	addrVlgCd: '',
	addrHusNo: '',
	postCd: ''
})

const options = ref([])
const addCodesData = ref([])

const dataFormRef = ref()

const dataRules = ref({
	addrTpCd: [{ required: true, message: '请选择地址类型', trigger: 'change' }],
	addCodes: [{ required: true, message: '请选择所在省市区', trigger: 'change' }],
	postCd: [
		{
			validator: (rule, value, callback) => {
				var reg = /^[0-9]{6}$/
				if (!value) {
					callback()
				} else if (reg.test(value)) {
					callback()
				} else {
					return callback(new Error('请输入正确的邮编'))
				}
			}
		}
	]
})

const init = async (data, empiId, adcdDatas) => {
	btnLoading.value = false
	visible.value = true
	options.value = []
	dataForm.addCodes = []

	// console.log(adcdDatas)
	addCodesData.value = adcdDatas

	nextTick(async () => {
		if (dataFormRef.value) {
			dataFormRef.value.resetFields()
		}

		// await getProvinceList()

		dataForm.empi = empiId
		if (data) {
			Object.assign(dataForm, data)

			if (dataForm.addrPrvCd) {
				dataForm.addCodes = [Number(dataForm.addrPrvCd), Number(dataForm.addrCtyCd), Number(dataForm.addrCntyCd)]

				dataForm.addrTwnCd = data.addrTwnCd ? parseFloat(data.addrTwnCd) : ''
				dataForm.addrVlgCd = data.addrVlgCd ? parseFloat(data.addrVlgCd) : ''

				// const firstItem = addCodesData.value.find(v => {
				// 	return v.value == dataForm.addrPrvCd
				// })
				// const second = await getAddressCode(dataForm.addrPrvCd, false)

				// firstItem.children = second
				// levelData2.value = second

				// const secondItem = second.find(v => {
				// 	return v.value == dataForm.addrCtyCd
				// })

				// const thrid = await getAddressCode(dataForm.addrCtyCd, true)

				// secondItem.children = thrid
				// levelData3.value = thrid

				getStreetList(dataForm.addrCntyCd)
			}
		} else {
			dataForm.id = ''
		}
	})
}

const levelData2 = ref([])
const levelData3 = ref([])

const addressData = {
	lazy: true,
	lazyLoad: (node, resolve) => {
		const { value, level, children } = node
		// if (level == 0) {
		// 	resolve(addCodesData.value)
		// }

		useDictProviceDetailApi({ pcode: node.level == 0 ? 0 : node.value }).then(res => {
			if (node.children && node.children.length > 0) return
			const list = res.data.map(v => {
				return {
					label: v.name,
					value: v.code,
					leaf: level >= 2
				}
			})
			resolve(list)
		})
		// if (level == 0) {
		// 	resolve(addCodesData.value)
		// } else {
		// 	console.log(value, level, children)

		// 	getAddressCode(level ? value : 0, level >= 2).then((res) => {
		// 		if (level === 1) {
		// 			if (children && children.length > 0) return
		// 			levelData2.value = res
		// 		} else if (level === 2) {
		// 			levelData3.value = res
		// 		}
		// 		resolve(res)
		// 	})
		// }
	}
}

const getAddressCode = (value, leaf) => {
	console.log(value)
	return new Promise(resolve => {
		const params = {
			pcode: value
		}

		useDictProviceDetailApi(params).then(res => {
			const list = res.data.map(v => {
				return {
					label: v.name,
					value: v.code,
					leaf: leaf
				}
			})
			resolve(list)
		})
	})
}

const adcdChange = value => {
	dataForm.addrTwnCd = ''
	dataForm.addrVlgCd = ''
	streetList.value = []
	villageList.value = []

	dataForm.addCodes = value
	getStreetList(value[2])
}

// 街道
const streetList = ref([])
const getStreetList = (adcdId: any) => {
	streetList.value = []
	useDictProviceDetailApi({
		pcode: adcdId
	}).then(res => {
		streetList.value = res.data

		if (res.data.length) {
			if (dataForm.id) {
			} else {
			}

			if (dataForm.addrTwnCd) {
				getVillageList(dataForm.addrTwnCd)
			}
		}
	})
}

const streeChange = e => {
	dataForm.addrTwnCd = e

	dataForm.addrVlgCd = ''
	getVillageList(e)
}

// 村
const villageList = ref([])
const getVillageList = (adcdId: any) => {
	villageList.value = []
	useDictProviceDetailApi({
		pcode: adcdId
	}).then(res => {
		villageList.value = res.data
	})
}

//

const subFormHandle = () => {
	dataFormRef.value.validate(valid => {
		if (!valid) return
		btnLoading.value = true

		dataForm.addrPrvCd = dataForm.addCodes[0]
		dataForm.addrCtyCd = dataForm.addCodes[1]
		dataForm.addrCntyCd = dataForm.addCodes[2]

		savePatientAddress(dataForm)
			.then(res => {
				ElMessage.success('操作成功')
				btnLoading.value = false
				visible.value = false
				emit('close')
			})
			.catch(() => {
				btnLoading.value = false
			})
	})
}

defineExpose({
	init
})
</script>
<style lang="less" scoped></style>
